from django.contrib.contenttypes.models import ContentType
from django.template import add_to_builtins

TYPE_KEY = "_t"
OBJ_KEY = "_o"
START_KEY = "_s"
END_KEY = "_e"
DIM_KEY = "_d"
SCROLL_KEY = "_c"
RETURN_KEY = "_r"

class UrlMiddleware(object):
    """
    This class works in conjunction with the pp_url tag to populate requests with
    a model instance and/or a numerical range that can be used in pagination.

    This also maintains a queue of recently visited urls, that can be used as 'breadcrumbs'
        for ease in navigation.
    """

    def process_request(self, request):

        content_type_id = request.GET.get(TYPE_KEY)
        obj_id = request.GET.get(OBJ_KEY)
        start = request.GET.get(START_KEY)
        end = request.GET.get(END_KEY)
        dim = request.GET.get(DIM_KEY)
        scroll_to = request.GET.get(SCROLL_KEY)
        returnurl = request.GET.get(RETURN_KEY)

        if content_type_id is not None and obj_id is not None:
            content_type   = ContentType.objects.get(pk=content_type_id)
            try: request.object = content_type.get_object_for_this_type(pk=obj_id)
            except: pass
        
        if start is not None and end is not None:
            request.start = int(start) 
            request.end = int(end)
            rangelist = []
            div = int(start) / 100.0
            multiple = round(div)
            start_range = int(100 * multiple)
            n = 0
            for itr in range(start_range, start_range + 100, 20):
                rangelist.append([itr, itr+20, n])
                n+=1
            request.rangelist = rangelist
            
        if returnurl is not None:
            request.returnurl = returnurl

        if dim is not None:
            request.dimension = dim
        
        if scroll_to:
            request.scroll_to = True
            request.scroll_to_div = scroll_to

        request_path = request.get_full_path()
        name = request_path
        if request_path != '/favicon.ico' and request_path[0:7] != '/submit' and request_path != '/vote/' and request_path != '/logout/':
                try: request.session['currently_visiting'] 
                except: request.session['currently_visiting'] = request_path
                if request.session['currently_visiting'] != request_path:
                    try:
                        visit_list = list(request.session['last_visited'])
                    except:                
                        visit_list = []
                    if len(visit_list) >= 8:
                        try: visit_list.pop(0)
                        except: pass #no visit_list
                    try: #name logic goes here
                          #you have request.object and content_type  
                        if obj_id == None:
                            if request.path[0:4] == '/iss': t_nam = "issues"
                            elif request.path[0:4] == '/sol': t_nam = "solutions"
                            try: name = request.dimension + " " + t_nam
                            except: name = "hot " + t_nam
                        elif request_path[0:4] == '/use':
                            name = str(request.object.username).lower() + " profile"
                        elif str(content_type) == u'issue' and request_path[0:4] == '/sol': 
                            try: name = request.dimension + " " + str(request.object.name).lower() + " solutions"
                            except: name = "hot " + str(request.object.name).lower() + " solutions"
                        elif str(content_type) == u'topic' and request_path[0:4] == '/iss': 
                            try: name = request.dimension + " " + str(request.object.text).lower() + " issues"
                            except: name = "hot " + str(request.object.text).lower() + "issues"
                        elif str(content_type) == u'issue' and request_path[0:4] == '/iss': 
                            name = "iss. detail: " + str(request.object.name).lower()
                        elif str(content_type) == u'solution' and request.path[0:4] == '/sol':
                            name = "sol. detail: " + str(request.object.name).lower()    
                        elif str(content_type) == u'argument' and request.path[0:4] == '/arg':
                            name = "arg. detail: " + str(request.object.name).lower()
                    except:
                        name = None
                    try: 
                        if name != None:
                            try: 
                                if visit_list[-1][0] != name: visit_list.append((name, request_path))
                            except: visit_list.append((name, request_path))
                    except KeyError: pass #first visit
                    request.session['last_visited'] = visit_list
        if request_path != '/favicon.ico' and request_path[0:7] != '/submit' and request_path != '/vote/' and request_path != '/logout/':
            request.session['currently_visiting'] = request_path
            
class AddToBuiltinsMiddleware(object):
    def process_request(self, request):
        # This adds all tags registered separately through native_tags to the builtins
        add_to_builtins('native_tags.templatetags.native')
